package info.batcloud.fanli.core.service.impl;

import info.batcloud.fanli.core.entity.TaobaoAccount;
import info.batcloud.fanli.core.repository.TaobaoAccountRepository;
import info.batcloud.fanli.core.service.TaobaoAccountService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.Date;

@Service
public class TaobaoAccountServiceImpl implements TaobaoAccountService {

    @Inject
    private TaobaoAccountRepository taobaoAccountRepository;

    @Override
    public void saveUserTaobaoAccount(long userId, TaobaoAccountSaveParam param) {
        TaobaoAccount taobaoAccount = taobaoAccountRepository.findByUserId(userId);
        if (taobaoAccount == null) {
            taobaoAccount = new TaobaoAccount();
            taobaoAccount.setUserId(userId);
            taobaoAccount.setCreateTime(new Date());
            taobaoAccount.setLoginTimes(0);
            taobaoAccount.setLastLoginTime(new Date());
        }
        BeanUtils.copyProperties(param, taobaoAccount);
        taobaoAccount.setUpdateTime(new Date());
        taobaoAccountRepository.save(taobaoAccount);
    }

    @Override
    public String findUserAccessToken(long userId) {
        TaobaoAccount taobaoAccount = taobaoAccountRepository.findByUserId(userId);
        if (taobaoAccount == null || taobaoAccount.getExpiresIn().before(new Date())) {
            return null;
        }
        return taobaoAccount.getAccessToken();
    }
}
